package com.example.autopera.线程池;

import java.util.concurrent.*;

/**
 * @author Code_lemon
 * @version 1.0.0
 * @description TODO
 * @date 2024/10/23 15:53
 * @title CustomThreadPoolExample
 */
public class CustomThreadPoolExample {

    public static void main(String[] args) {
        // 常驻线程
        int corePoolSize = 2;
        // 最大线程
        int maximumPoolSize = 5;
        // 线程存活时间
        long keepAliveTime = 5L;
        // 时间单位
        TimeUnit unit = TimeUnit.SECONDS;
        // 阻塞队列长度
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(3);
        // 线程工厂
        ThreadFactory factory = Executors.defaultThreadFactory();
        // 拒绝策略
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();

        // 定义个性化线程池
        ExecutorService threadPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                 workQueue,
                factory,
                handler
        );


        try {
            for (int i = 1; i <= 20; i++) {
                // 创建线程池，执行任务
                threadPool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + "办理业务");
                });
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 关闭线程池
            threadPool.shutdown();
        }
    }
}
